import paho.mqtt.client as mqtt

# 当客户端接收到连接响应时触发的回调函数
def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    # 订阅指定的主题
    client.subscribe("test/topic")

# 当客户端接收到消息时触发的回调函数
def on_message(client, userdata, msg):
    print(f"Received message: {msg.payload.decode()} on topic {msg.topic}")

# MQTT Broker 的地址和端口
broker_address = "localhost"  # 替换为实际的 Broker 地址
broker_port = 1883  # 默认端口

# 创建 MQTT 客户端实例
client = mqtt.Client(client_id="PythonSubscriber")

# 绑定回调函数
client.on_connect = on_connect
client.on_message = on_message

# 连接到 MQTT Broker
client.connect(broker_address, broker_port)

# 开始循环以保持连接并接收消息
client.loop_forever()
